package com.bay1ts.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by chenuu on 2016/3/16.
 * 2016年3月16日21:28:44
 * 改名字了，改成了success重定向策略，说明还有个failure策略，这样就解决了安卓等设备无脑验证通过的问题了
 */
public class CustomRedirectStategy implements RedirectStrategy {
    protected final Log logger = LogFactory.getLog(getClass());

    private boolean contextRelative;
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
        if(request.getHeader("Device")!=null&&request.getHeader("Device").equals("android-basicf")){
            response.setContentType("application/json");
            String json="{\"result\":\""+url+"\"}";
            if (logger.isDebugEnabled()) {
                logger.debug("Sending Json data"+json);
            }
            response.getWriter().write(json);
        }else {
            String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
            redirectUrl = response.encodeRedirectURL(redirectUrl);

            if (logger.isDebugEnabled()) {
                logger.debug("Redirecting to '" + redirectUrl + "'");
            }
            response.sendRedirect(redirectUrl);
        }
    }
    private String calculateRedirectUrl(String contextPath, String url) {
        if (!UrlUtils.isAbsoluteUrl(url)) {
            if (contextRelative) {
                return url;
            }
            else {
                return contextPath + url;
            }
        }

        // Full URL, including http(s)://

        if (!contextRelative) {
            return url;
        }

        // Calculate the relative URL from the fully qualified URL, minus the last
        // occurrence of the scheme and base context.
        url = url.substring(url.lastIndexOf("://") + 3); // strip off scheme
        url = url.substring(url.indexOf(contextPath) + contextPath.length());

        if (url.length() > 1 && url.charAt(0) == '/') {
            url = url.substring(1);
        }

        return url;
    }

    /**
     * If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol
     * and context path (defaults to <tt>false</tt>).
     */
    public void setContextRelative(boolean useRelativeContext) {
        this.contextRelative = useRelativeContext;
    }
}
